package com.open.capacity.user.controller;

import com.open.capacity.common.controller.UploadController;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysFile;
import com.open.capacity.user.service.SysFileService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 附件管理
 */
@RequestMapping("files")
@RestController
public class SysFileController {

    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;


    @Autowired
    private SysFileService fileService;


    /**
     * 查询附件
     *
     * @param folderId
     * @return
     */
    @GetMapping("/list")
    public Result<List<SysFile>> findList(String folderId) {
        List<SysFile> list = fileService.findByFolderId(folderId);
        return Result.succeed(list);
    }


    /**
     * 获取数据
     */
    @RequestMapping("/findById")
    public Result<SysFile> findById(String fileId) {
        SysFile file = fileService.findById(fileId);
        return Result.succeed(file);
    }

    /**
     * 查询附件名称
     *
     * @param folderId
     * @return
     */
    @GetMapping("/getNames")
    public Result<String> getNames(String folderId) {
        String name = "";
        if (StringUtil.isNotEmpty(folderId)) {
            List<SysFile> list = fileService.findByFolderId(folderId);
            for (SysFile item : list) {
                if (StringUtil.isEmpty(name)) {
                    name += item.getName();
                } else {
                    name += "," + item.getName();
                }
            }
        }
        return Result.succeed(name);
    }


    /**
     * 新增
     *
     * @param file
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody SysFile file) {
        int count = fileService.save(file);
        return Result.succeed(count);
    }

    /**
     * 批量新增
     *
     * @param folderId
     * @return
     */
    @PostMapping("/saveFiles")
    public Result saveFiles(@RequestBody SysFile[] files, String folderId) {
        int count = fileService.saveFiles(files, folderId);
        return Result.succeed(count);
    }

    /**
     * 删除
     *
     * @param id
     */
    @PostMapping("/delete")
    public Result delete(String id) {
        try {
            fileService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }

    /**
     * 删除
     *
     * @param foderId
     */
    @PostMapping("/deleteByFolderId")
    public Result deleteByFolderId(String foderId) {
        try {
            fileService.deleteByFolderId(foderId);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }

    /**
     * 通用下载请求
     */
    @RequestMapping("/download")
    public void fileDownload(String fileId, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            SysFile file = fileService.findById(fileId);
            String fileName = file.getName();
            String realFileName = file.getUrl().substring(file.getUrl().lastIndexOf("profile") + 8);
            String filePath = fileuploadPath + File.separator + realFileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete != null && delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
